package com.unience.ec2.eclipse.view;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.eclipse.ui.part.ViewPart;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class Ec2ShellView extends ViewPart {
	public static final String ID_VIEW = "com.unience.ec2.eclipse.view.Ec2ShellView"; //$NON-NLS-1$
	private Text textArea;
	private Button buttonConnect;
	private Text textInsntace;
	private Label Instance;

	Composite composite1;

	/**
	 * 
	 */
	public Ec2ShellView() {
		super();
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
	 */
	public void createPartControl(Composite parent) {
		{
			parent.setSize(802, 425);
			{
				composite1 = new Composite(parent, SWT.NULL);
				composite1.setLayout(null);
				{
					Instance = new Label(composite1, SWT.NONE);
					Instance.setText("Instance");
					Instance.setBounds(5, 10, 59, 17);
				}
				{
					textInsntace = new Text(composite1, SWT.NONE);
					textInsntace.setText("text1");
					textInsntace.setBounds(69, 10, 233, 17);
				}
				{
					buttonConnect = new Button(composite1, SWT.PUSH
							| SWT.CENTER);
					buttonConnect.setText("Connect");
					buttonConnect.setBounds(307, 5, 64, 27);
					buttonConnect.addMouseListener(new MouseAdapter() {
						public void mouseDown(MouseEvent evt) {
							buttonConnectMouseDown(evt);
						}
					});
				}
				{
					textArea = new Text(composite1, SWT.MULTI | SWT.WRAP);
					textArea.setBounds(13, 39, 777, 377);

				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#setFocus()
	 */
	public void setFocus() {
		// TODO Auto-generated method stub
	}

	/**
	 * Cleans up all resources created by this ViewPart.
	 */
	public void dispose() {
		super.dispose();
	}

	private void buttonConnectMouseDown(MouseEvent evt) {
		System.out.println("buttonConnect.mouseDown, event=" + evt);
		try {
			JSch jsch = new JSch();

			JFileChooser chooser = new JFileChooser();
			chooser.setDialogTitle("Choose your privatekey(ex. ~/.ssh/id_dsa)");
			chooser.setFileHidingEnabled(false);
			int returnVal = chooser.showOpenDialog(null);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				System.out.println("You chose "
						+ chooser.getSelectedFile().getAbsolutePath() + ".");
				jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath()
				// , "passphrase"
						);
			}

			String host = null;

			host = JOptionPane.showInputDialog("Enter username@hostname",
					System.getProperty("user.name") + "@localhost");

			String user = host.substring(0, host.indexOf('@'));
			host = host.substring(host.indexOf('@') + 1);

			Session session = jsch.getSession(user, host, 22);

			// username and passphrase will be given via UserInfo interface.
			UserInfo ui = new MyUserInfo();
			session.setUserInfo(ui);
			session.connect();

			Channel channel = session.openChannel("shell");

			OutputStream out = new OutputStream() {

				public void write(int b) throws IOException {
					if (textArea.isDisposed())
						return;
					textArea.append(String.valueOf((char) b));
				}
			};
			final PrintStream oldOut = System.out;
			System.setOut(new PrintStream(out));
			textArea.addDisposeListener(new DisposeListener() {
				public void widgetDisposed(DisposeEvent e) {
					System.setOut(oldOut);
				}
			});
			
			InputStream input = new InputStream(){
				int count = -1;
				 public int read(){
					int num =  textArea.getCharCount();
					
					if ( num > 0){
						count++;
						return textArea.getText().charAt(count);
						
					}else{
						return -1;
					}
				 }
			};
			
			System.setIn(input);
			

			channel.setInputStream(System.in);
			channel.setOutputStream(System.out);

			channel.connect();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
		public String getPassword() {
			return passwd;
		}

		public boolean promptYesNo(String str) {
			Object[] options = { "yes", "no" };
			int foo = JOptionPane.showOptionDialog(null, str, "Warning",
					JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
					null, options, options[0]);
			return foo == 0;
		}

		String passwd;
		JTextField passwordField = (JTextField) new JPasswordField(20);

		public String getPassphrase() {
			return null;
		}

		public boolean promptPassphrase(String message) {
			return true;
		}

		public boolean promptPassword(String message) {
			Object[] ob = { passwordField };
			int result = JOptionPane.showConfirmDialog(null, ob, message,
					JOptionPane.OK_CANCEL_OPTION);
			if (result == JOptionPane.OK_OPTION) {
				passwd = passwordField.getText();
				return true;
			} else {
				return false;
			}
		}

		public void showMessage(String message) {
			JOptionPane.showMessageDialog(null, message);
		}

		final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1, 1,
				GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 0, 0);
		private Container panel;

		public String[] promptKeyboardInteractive(String destination,
				String name, String instruction, String[] prompt, boolean[] echo) {
			panel = new JPanel();
			panel.setLayout(new GridBagLayout());

			gbc.weightx = 1.0;
			gbc.gridwidth = GridBagConstraints.REMAINDER;
			gbc.gridx = 0;
			panel.add(new JLabel(instruction), gbc);
			gbc.gridy++;

			gbc.gridwidth = GridBagConstraints.RELATIVE;

			JTextField[] texts = new JTextField[prompt.length];
			for (int i = 0; i < prompt.length; i++) {
				gbc.fill = GridBagConstraints.NONE;
				gbc.gridx = 0;
				gbc.weightx = 1;
				panel.add(new JLabel(prompt[i]), gbc);

				gbc.gridx = 1;
				gbc.fill = GridBagConstraints.HORIZONTAL;
				gbc.weighty = 1;
				if (echo[i]) {
					texts[i] = new JTextField(20);
				} else {
					texts[i] = new JPasswordField(20);
				}
				panel.add(texts[i], gbc);
				gbc.gridy++;
			}

			if (JOptionPane.showConfirmDialog(null, panel, destination + ": "
					+ name, JOptionPane.OK_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
				String[] response = new String[prompt.length];
				for (int i = 0; i < prompt.length; i++) {
					response[i] = texts[i].getText();
				}
				return response;
			} else {
				return null; // cancel
			}
		}
	}

}
